import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/view/Home.vue'
import Login from '@/view/Login.vue'
import ColumnDetail from '@/view/ColumnDetail.vue'
import ColumnWrite from '@/view/ColumnWrite.vue'
import store from '@/static/store/store'
import message from '@/static/plugins/message'
import SignUp from '@/view/SignUp.vue'
import Test from '@/view/Test.vue'
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: Home.name,
      component: Home
    },
    {
      path: '/login',
      name: Login.name,
      component: Login,
      meta: { redirectAlready: true }
    },
    {
      path: '/signup',
      name: SignUp.name,
      component: SignUp
    },
    // 动态路由，:id前要/
    {
      path: '/column/:id',
      name: ColumnDetail.name,
      component: ColumnDetail
    },
    {
      path: '/test',
      name: Test.name,
      component: Test
    },
    {
      path: '/column/write',
      name: ColumnWrite.name,
      component: ColumnWrite,
      meta: { needLogined: true }
    }
  ]
})

/**
 * 路由守卫
 */
router.beforeEach((to, from, next) => {
  if (to.meta.needLogined && !store.state.user.isLogined) {
    message.alert('您尚未登陆，请先登陆').then(
      res => {
        if (res === 'confirm') {
          next({ name: 'Login' })
        }
      })
    return
  } else if (to.meta.redirectAlready && store.state.user.isLogined) {
    next({ name: 'Home' })
    return
  }
  next()
})

export default router
